<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	/**
	 * @author Garry Willits
	 * @copyright 
	 * @date 10th May 2011
	 */
class ImagesAdmin  extends CI_Controller{

	public $maxthumbwidth = 140;
	
	public $maximagewidth = 900;
	
	public $uploadpath = 'uploads/';
	
	public $deletepath = 'uploads';
	
	public $commandPath = "admin/images/";
	
	protected  $illegalCatDel = FALSE;
	
	protected $category_options = array();
	/*
	 * doesn't mean is bust means is doing something
	 */
	public $working = true;
	public function __construct()
	{   
		parent::__construct();
		$this->load->database();
		$this->display = new Display();
		$this->load->database();
		$this->load->helper('url');
		$this->load->library('form_validation');
		$this->load->library('encrypt');
		$this->load->helper(array('form', 'url','path','file','Image_helper'));
		$this->load->library('form_validation');
		$this->load->model('GalleryModel','gmodel');
		$this->display->scripts = 'jquery.js';
		$this->display->scripts = 'jquery-ui.js';
		$this->display->scripts = 'jquery.lightbox-0.5.js';
		$this->display->scripts = 'uiinit.js'; 
		$this->display->styles = 'ui';
		$this->display->styles = 'themes/smoothness/jquery.ui.all';
		$this->display->styles = 'lightbox';
		$this->display->styles = 'common';
		$upload = $this->input->post('upload_submitted');
		$this->display->errors = null;
		$category_num = $this->uri->segment(4, 0);
		$page_num = $this->uri->segment(6, 0);
		$this->display->form_address = $this->commandPath."catID/".$category_num."/page/$page_num";
		$this->display->cat_select = $category_num;
		$cancel = $this->input->post('cancel');
		$deleteCat = $this->input->post('deleteCat');
			// offer a delete button for category if empty
		$this->display->no_existing = FALSE;
		if( $this->gmodel->countImagesInCategory( $this->gmodel->getCategory($this->display->cat_select)->id ) == 0 ){
			$this->display->no_existing = TRUE;
		}
		if( !EMPTY($cancel)){
			delete_files( set_realpath( $this->deletepath ) );
			unset( $_SESSION[ 'UPLOAD_DATA' ] );
			redirect($this->display->form_address);
		}
		if( !EMPTY($deleteCat)){
			if(!$this->gmodel->deleteCategory( $this->gmodel->getCategory($this->display->cat_select)->id ) ){
				$this->display->uploaderrors = array('error' => 'You may not delete the default category' );
				unset( $upload );
			}
 			else {
 				redirect($this->commandPath);
 			}
		}
		$query = $this->gmodel->getCategories();
			$this->category_options = array();
		
			foreach ($query as $row)
			{
			   $this->category_options[ $row->id ]= $row->name;
			}
		if( !empty($upload) ){
			$this->doUpload();
		}else if( !empty($_SESSION[ 'UPLOAD_DATA' ])){
			$this->load->library('form_validation');
			$this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[2]|max_length[40]|xss_clean');
			$this->form_validation->set_rules('description', 'Description', 'trim|xss_clean');
			$this->form_validation->set_rules('short_description', 'short_Description', 'trim|xss_clean');
			//$this->form_validation->set_rules('date_created', 'Date Created', 'trim|xss_clean');
			$this->form_validation->set_rules('date_created', 'Date', 'callback_validateDate');
			$this->form_validation->set_rules('new_cat', 'New Category', 'trim|xss_clean|callback_validateCategory');
			$this->form_validation->set_rules('price', 'Price', 'numeric|trim|xss_clean');
			$this->display->imgdata = $_SESSION[ 'UPLOAD_DATA' ];
			
				if ($this->form_validation->run() == FALSE )
				{
					$this->display->errors = $this->form_validation->_error_fields;
					$this->doProcess();
				}
				else {
					
					$date = $this->input->post('date_created');
					if( $date!=""){
						$dayofmonth = substr($date,0,2);
						$month = substr($date,3,2);
						$year = substr($date,6,4);
						$date_format = "$year-$dayofmonth-$month";
					}
					else {
						$date_format=NULL;
					}
					$category_id=0;
					$cat_name = "";
					$new_cat = $this->input->post('new_cat');
					if( !empty( $new_cat ) ){
						$cat_name = $new_cat;
						// check to see if we need to create a directory
						if ( !get_file_info( "images/".$cat_name)  ){ // check if Client directory exists if not CREATE IT
				            mkdir( set_realpath("images/".$cat_name) , DIR_WRITE_MODE);
				        }
						$category_id=$this->gmodel->newCategory($cat_name);
					}
					else {
						$category_id = $this->input->post('categories');
						$cat_name = $this->category_options[ $category_id ];
					}
					// create a folder for this image
					$img_path= "images/".$cat_name."/".$_SESSION[ 'UPLOAD_DATA' ][ 'raw_name' ];
					if( !read_file(set_realpath($img_path))){
						mkdir(set_realpath($img_path), DIR_WRITE_MODE);
					}
					$img_dat = "$img_path/".$_SESSION[ 'UPLOAD_DATA' ][ 'orig_name' ];
					$this->gmodel->newImage($this->input->post('title'),$img_dat,$_SESSION[ 'UPLOAD_DATA' ][ 'image_width' ],$_SESSION[ 'UPLOAD_DATA' ][ 'image_height'],$this->input->post('description'),$this->input->post('short_description'),$date_format,$category_id );
					// file actions
					// ok first pass on image
					$new_file = 'images\default\\'.$_SESSION[ 'UPLOAD_DATA' ][ 'orig_name' ];
					if( read_file( $new_file )!= FALSE){
						@unlink( $new_file );
					}
					
				rename( $_SESSION[ 'UPLOAD_DATA' ][ 'full_path' ], set_realpath( "$img_path/").$_SESSION[ 'UPLOAD_DATA' ][ 'orig_name' ] );
				delete_files( set_realpath( $this->deletepath ) );
				unset( $_SESSION[ 'UPLOAD_DATA' ] );
				// if a successful upload then not possible to delete category
				$this->display->filecreated = TRUE;
				// Check to see if a new category has been created
				$this->getUpload();
			} 			
		}
		else{
			$this->getUpload();
		}
		$this->display->finalize();
	}
	/**
	 * 
	 * Starts the ball rolling
	 */
	protected  function getUpload(){
		$this->display->base = "imageAdmin/processImages";
		$this->working = false;
	}
	/**
	 * Upload an image file
	 */
	protected function doUpload(){
	    $config['upload_path'] = $this->uploadpath;
	    $config['create_thumb'] = FALSE;
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size']	= '4000';
		$config['max_width']  = '4000';
		$config['max_height']  = '3000';
		$this->load->library('upload', $config);
		$this->upload->initialize($config);
		if ( ! $this->upload->do_upload('imgupload'))
		{
			$error = array('error' => $this->upload->display_errors());
			$this->display->base = "imageAdmin/processImages";
			$this->display->uploaderrors = $error;
		}
		else
		{
			$data = $this->upload->data();
			// create a thumb
			if( $data['image_width'] > $this->maxthumbwidth ){
				$resize = $this->maxthumbwidth;
			}
			else {
				$resize = $data['image_width'];
			}
			resize( $data['full_path'],$resize,$data['image_width']/100*$resize,$this->uploadpath.$data['raw_name']."_thumb".$data['file_ext'] );
			// check to see if we need to shrink it 
			if( $data['image_width'] > $this->maximagewidth ){
				resize( $data['full_path'],$this->maximagewidth,$data['image_width']/100*$this->maximagewidth,$data['full_path'] );
			}
			else if ($data['image_height'] > $this->maximagewidth){
				resize( $data['full_path'],$data['image_height']/100*$this->maximagewidth,$this->maximagewidth,$data['full_path']);
			}
			$data[ 'thumb' ] = $data['raw_name']."_thumb".$data['file_ext']; 
			$data[ 'thumb_width' ] = $resize;
			$this->display->imgdata = $data;
			$_SESSION[ 'UPLOAD_DATA' ]= $data;
			
			$this->doProcess();
		}
	}
	/*
	 * Process the upload action
	 */
	protected function doProcess(){
			$this->display->options = $this->category_options;
			$this->display->base = "imageAdmin/processImages2";
	}
	
	/**
	 * 
	 * validates this string as uk date
	 * @param string $datein
	 */
	public function validateDate( $datein ){
		if( $datein == '' )return true;
		$valid = false;
		$arr=split("/",$datein); // splitting the array
		if( count( $arr ) == 3 ){
			$mm=$arr[0]; // first element of the array is month
			$dd=$arr[1]; // second element is date
			$yy=substr ($arr[2],2); // third element is year
			If(checkdate($mm,$dd,$yy)){
				$valid = true;
			}
		}
		if( !$valid ){
			$this->form_validation->set_message('validateDate', '%s  must be in the date format dd/mm/yy');
		}
		return $valid ;
	}
	/**
	 * 
	 * Checks to see this category doesn't exist
	 * @param unknown_type $category
	 */
	public function validateCategory( $category ){
		if ($this->gmodel->checkGalleryExists($category)){
			$this->form_validation->set_message('validateCategory', "The category $category already exists!");
			return false;
		}
		return true;
	}
}
